#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
class BulkInserter(object):
  INSERT_BATCH_SIZE = 100000
  def __init__(self, conn, query, query_arity):
    self.conn = conn
    self.bulk_insert_queue = []
    self.ninserts = 0
    self.query = query
    self.query_arg_string = ' (' + ','.join(('%s',) * query_arity) + ')'

  def insert(self, args):
    self.bulk_insert_queue.extend(args)
    self.ninserts += 1
    if self.ninserts == BulkInserter.INSERT_BATCH_SIZE:
      self._actually_insert()

  def done(self):
    if self.ninserts:
      self._actually_insert()

  def _actually_insert(self):
    c = self.conn.cursor()
    full_query = self.query + ','.join((self.query_arg_string,) * self.ninserts)
    c.execute(full_query, self.bulk_insert_queue)
    self.ninserts = 0
    self.bulk_insert_queue = []
    
try:
  from cybulk_inserter import BulkInserter
except ImportError:
  pass
